package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.User;
import cn.wolfcode.rbac.mapper.UserMapper;
import cn.wolfcode.rbac.query.PageResult;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void saveOrUpdate(User user) {
        if (user.getId()!=null){
            // id不为空,说明此时调用的是修改操作
            // Update 表名 set name=?,sn=? where id=?;
            userMapper.updateByPrimaryKey(user);
        }else {
            // id为空,说明此时调用的是保存操作
            // insert into 表名(name,sn) values(?,?)
            userMapper.insert(user);
        }
    }

    @Override
    public void delete(Long id) {
        userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public User getOne(Long id) {
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    public List<User> listAll() {
        List<User> users = userMapper.selectAll();
        return users;
    }

    @Override
    public PageResult query(QueryObject qo) {
        //查询总条数
        int totalCount = userMapper.queryForCount();
        //查询带有分页效果的结果集
        if (totalCount == 0){
            //查不出数据,调用的是pageResult类中的缺参构造器
            return new PageResult(qo.getCurrentPage(),qo.getPageSize());
        }

        List<User> data = userMapper.queryForList(qo);
        return new PageResult(data,totalCount,qo.getCurrentPage(),qo.getPageSize());
    }
}
